<template>
  <view class="chat-container">
    <!-- 顶部导航 -->
    <uv-navbar
      title="AI问诊助手"
      :safeAreaInsetTop="true"
      bgColor="linear-gradient(135deg, #e0e7ff, #f0f4ff)"
      titleColor="#3b4a8c"
      :border="true"
      borderColor="#e0e7ff"
      height="100px"
    ></uv-navbar>

    <!-- 对话区域 -->
    <view class="chat-messages" ref="chatContainer">
      <view class="system-message">
        <text>我是您的健康助手，可以为您解答健康相关问题</text>
      </view>

      <view 
        v-for="(msg, index) in messages" 
        :key="index" 
        :class="['message-item', msg.role === 'assistant' ? 'ai-message' : 'user-message']"
      >
        <view class="avatar">
          <uv-icon 
            :name="msg.role === 'assistant' ? 'robot' : 'user'" 
            size="24" 
            :color="msg.role === 'assistant' ? '#6366f1' : '#ffffff'"
          ></uv-icon>
        </view>
        <view class="message-content">
          <text>{{ msg.content }}</text>
        </view>
      </view>

      <view v-if="isLoading" class="message-item ai-message">
        <view class="avatar">
          <uv-icon name="robot" size="24" color="#6366f1"></uv-icon>
        </view>
        <view class="message-content loading">
          <view class="loading-dot"></view>
          <view class="loading-dot"></view>
          <view class="loading-dot"></view>
        </view>
      </view>
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <textarea
        v-model="userInput"
        placeholder="请输入您的问题..."
        class="chat-input"
        @confirm="sendMessage"
      ></textarea>
      <button class="send-btn" @click="sendMessage" :disabled="!userInput || isLoading">
        <uv-icon name="send" size="18" color="#ffffff"></uv-icon>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
//发送网络请求

// 配置axios实例（针对DeepSeek API）
const apiClient = axios.create({
  baseURL: 'https://api.deepseek.com/v1',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'sk-2bb3ca0816e1416ba2b1ba3071e37a68' // API密钥
  }
});

// 状态管理
const messages = ref([]);
const userInput = ref('');
const isLoading = ref(false);
const chatContainer = ref(null);

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return;

  // 添加用户消息
  const userMessage = {
    role: "user",
    content: userInput.value.trim()
  };
  messages.value.push(userMessage);
  userInput.value = '';
  scrollToBottom();

  // 调用AI接口
  isLoading.value = true;
  try {
    // 使用axios发送请求（替代openai SDK的fetch调用）
    const response = await apiClient.post('/chat/completions', {
      model: "deepseek-chat",
      messages: [
        {
          role: "system",
          content: "你是一位专业的健康助手，为用户提供健康咨询和建议，但不能替代医生诊断。记住，你要用很友好的语气和病人诉说。"
        },
        ...messages.value
      ]
    });

    // 处理AI回复
    const aiMessage = {
      role: "assistant",
      content: response.data.choices[0].message.content
    };
    messages.value.push(aiMessage);

  } catch (err) {
    console.error("API请求错误：", err);
    messages.value.push({
      role: "assistant",
      content: `请求失败：${err.response?.data?.error?.message || err.message || '网络错误'}`
    });
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

// 页面加载时滚动到底部
onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped>
/* 样式保持不变，与之前的蓝紫色风格一致 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f9fafe;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  box-sizing: border-box;
}

.system-message {
  margin: 15rpx auto;
  padding: 10rpx 20rpx;
  background-color: #eef2ff;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #5a64a9;
  text-align: center;
  max-width: 80%;
}

.message-item {
  display: flex;
  margin-bottom: 20rpx;
  max-width: 85%;
  animation: fadeIn 0.3s ease;
}

.ai-message {
  align-self: flex-start;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
  flex-shrink: 0;
  background-color: #e0e7ff;
}

.user-message .avatar {
  margin-right: 0;
  margin-left: 15rpx;
  background-color: #6366f1;
}

.message-content {
  padding: 20rpx 25rpx;
  border-radius: 20rpx;
  line-height: 1.6;
  font-size: 28rpx;
  word-break: break-all;
}

.ai-message .message-content {
  background-color: #ffffff;
  color: #3b4a8c;
  border: 1px solid #e0e7ff;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.08);
  border-top-left-radius: 8rpx;
}

.user-message .message-content {
  background-color: #6366f1;
  color: #ffffff;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.15);
  border-top-right-radius: 8rpx;
}

.input-area {
  display: flex;
  padding: 15rpx;
  background-color: #ffffff;
  border-top: 1px solid #e0e7ff;
}

.chat-input {
  flex: 1;
  min-height: 80rpx;
  max-height: 200rpx;
  padding: 20rpx;
  border-radius: 40rpx;
  background-color: #f0f4ff;
  border: 1px solid #e0e7ff;
  font-size: 28rpx;
  resize: none;
  box-sizing: border-box;
  color: #3b4a8c;
}

.chat-input::placeholder {
  color: #a0a7cc;
}

.send-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #6366f1;
  color: white;
  margin-left: 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2);
  transition: background-color 0.3s ease;
}

.send-btn:disabled {
  background-color: #a0a7cc;
  box-shadow: none;
}

.send-btn:active {
  background-color: #5255d4;
}

.loading {
  display: flex;
  gap: 10rpx;
  padding: 25rpx;
}

.loading-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #6366f1;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style>
